import html2canvas from "html2canvas"
import JSPDF from "jspdf"

/**
  * printId @String 打印区域id
  * isTemplateIframe @Boolean 打印区域是否是template
  * printW @Number 打印纸张宽
  * printH @Number 打印纸张高
*/

export const printpdf =  function(printId, isTemplateIframe, printW, printH) {
        return new Promise((resolve, reject) => {
          let dom;
          // let iframes;
          let templateIframeContent;
          if (isTemplateIframe) {
            document.getElementById(printId).contentWindow.postMessage("getIframeContent", "*");
            window.addEventListener("message", (e) => {
              // eslint-disable-next-line no-prototype-builtins
              if (e.data.hasOwnProperty("templateIframe")) {
                const data = e.data["templateIframe"];
                const dataDOM = new DOMParser().parseFromString(data, "text/html");
                templateIframeContent = dataDOM.documentElement;
              }
            });
            setTimeout(() => {
              if (templateIframeContent) {
                // dom = document.getElementById(printId).contentWindow.document.querySelector(".flex-container");
                dom = templateIframeContent.querySelector(".flex-container");
                // iframes = document.getElementById(printId).contentWindow.document.getElementsByTagName("iframe");
                // print(dom, iframes);
                print(dom);
              }
            }, 1000)
          } else {
            dom = document.getElementById(printId);
            // iframes = document.getElementsByTagName("iframe");
            // print(dom, iframes);
            print(dom);
          }
  
          function print(dom) {
            const copyDom = dom.cloneNode(true);
            // const copyIframes = copyDom.querySelectorAll("iframe");
  
            /* if (iframes && iframes.length > 0) {
 48             for (let i = 0; i < iframes.length; i++) {
 49               const yushanInputComponent = iframes[i].closest(".YushanInputComponent");
 50               if (yushanInputComponent) {
 51                 const currentIframe = iframes[i];
 52                 const currentIframeContent = currentIframe.contentWindow.document.body;
 53                 const pNode = copyIframes[i].parentNode; // 移除copyDom下的iframe
 54                 pNode.removeChild(copyIframes[i]);
 55                 pNode.appendChild(currentIframeContent);
 56                 pNode.style.height = iframes[i].scrollHeight + "px";
 57                 continue;
 58               }
 59               const iframeDom = iframes[i].contentWindow.document.querySelector(".flex-container");
 60               const copyIframeDom = iframeDom.cloneNode(true); // 复制iframe
 61               const copyIframeNode = copyIframes[i];
 62               const parentNode = copyIframeNode.parentNode;
 63               parentNode.removeChild(copyIframeNode); // 移除原有的iframe
 64               parentNode.appendChild(copyIframeDom);
 65               parentNode.style.height = iframeDom.scrollHeight + "px";
 66             }
 67           } */
            copyDom.style.height = "auto";
            document.body.appendChild(copyDom);
            html2canvas(copyDom, {
              logging: false,
              useCORS: true
            }).then(function(canvas) {
              // 判断浏览器内核是否是IE
              if (!!window.ActiveXObject || "ActiveXObject" in window) {
                alert('截图打印暂不支持IE内核浏览器，请更换火狐或谷歌chrome内核浏览器，360等双核浏览器请切换至极速模式');
                return;
              }
  
              // var pdf = new JSPDF('p', 'mm', 'a4'); // A4纸，纵向
              var direction = 'p';// 默认纵向打印
              var size = 'a4'
              if (printW && printH) {
                size = [printW, printH];
                if (printW <= printH) {
                  direction = 'p'
                } else {
                  direction = 'l'
                }
              }
              var pdf = new JSPDF(direction, 'mm', size); // A4纸，纵向
              var ctx = canvas.getContext('2d');
              var a4w = printW ? (printW - 20) : 190;
              var a4h = printH ? (printH - 20) : 277; // A4大小，210mm x 297mm，四边各保留10mm的边距，显示区域190x277
              var imgHeight = Math.floor(a4h * canvas.width / a4w); // 按A4显示比例换算一页图像的像素高度
              var renderedHeight = 0;
  
              while (renderedHeight < canvas.height) {
                var page = document.createElement("canvas");
               page.width = canvas.width;
               page.height = Math.min(imgHeight, canvas.height - renderedHeight); // 可能内容不足一页
 
               // 用getImageData剪裁指定区域，并画到前面建立的canvas对象中
               page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight,
                 canvas.height - renderedHeight)), 0, 0);
               pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 10, a4w, Math.min(a4h, a4w * page.height /
                 page.width)); // 添加图像到页面，保留10mm边距
 
               renderedHeight += imgHeight;
               if (renderedHeight < canvas.height) {
                 pdf.addPage();
               } // 若是后面还有内容，添加一个空页
               page.remove();
             }
             const link = window.URL.createObjectURL(pdf.output('blob'));
             window.open(link);
             document.body.removeChild(copyDom);
             resolve();
           })
         }
})
}


export const savepdf =  function(printId, isTemplateIframe, printW, printH) {
        return new Promise((resolve, reject) => {
          let dom;
          // let iframes;
          let templateIframeContent;
          if (isTemplateIframe) {
            document.getElementById(printId).contentWindow.postMessage("getIframeContent", "*");
            window.addEventListener("message", (e) => {
              // eslint-disable-next-line no-prototype-builtins
              if (e.data.hasOwnProperty("templateIframe")) {
                const data = e.data["templateIframe"];
                const dataDOM = new DOMParser().parseFromString(data, "text/html");
                templateIframeContent = dataDOM.documentElement;
              }
            });
            setTimeout(() => {
              if (templateIframeContent) {
                // dom = document.getElementById(printId).contentWindow.document.querySelector(".flex-container");
                dom = templateIframeContent.querySelector(".flex-container");
                // iframes = document.getElementById(printId).contentWindow.document.getElementsByTagName("iframe");
                // print(dom, iframes);
                print(dom);
              }
            }, 1000)
          } else {
            dom = document.getElementById(printId);
            // iframes = document.getElementsByTagName("iframe");
            // print(dom, iframes);
            print(dom);
          }
  
          function print(dom) {
            const copyDom = dom.cloneNode(true);

            copyDom.style.height = "auto";
            document.body.appendChild(copyDom);
            html2canvas(copyDom, {
              logging: false,
              useCORS: true
            }).then(function(canvas) {
              // 判断浏览器内核是否是IE
              if (!!window.ActiveXObject || "ActiveXObject" in window) {
                alert('截图打印暂不支持IE内核浏览器，请更换火狐或谷歌chrome内核浏览器，360等双核浏览器请切换至极速模式');
                return;
              }
  
              // var pdf = new JSPDF('p', 'mm', 'a4'); // A4纸，纵向
              var direction = 'p';// 默认纵向打印
              var size = 'a4'
              if (printW && printH) {
                size = [printW, printH];
                if (printW <= printH) {
                  direction = 'p'
                } else {
                  direction = 'l'
                }
              }
              var pdf = new JSPDF(direction, 'mm', size); // A4纸，纵向
              var ctx = canvas.getContext('2d');
              var a4w = printW ? (printW - 20) : 190;
              var a4h = printH ? (printH - 20) : 277; // A4大小，210mm x 297mm，四边各保留10mm的边距，显示区域190x277
              var imgHeight = Math.floor(a4h * canvas.width / a4w); // 按A4显示比例换算一页图像的像素高度
              var renderedHeight = 0;
  
              while (renderedHeight < canvas.height) {
                var page = document.createElement("canvas");
               page.width = canvas.width;
               page.height = Math.min(imgHeight, canvas.height - renderedHeight); // 可能内容不足一页
 
               // 用getImageData剪裁指定区域，并画到前面建立的canvas对象中
               page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight,
                 canvas.height - renderedHeight)), 0, 0);
               pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 10, a4w, Math.min(a4h, a4w * page.height /
                 page.width)); // 添加图像到页面，保留10mm边距
 
               renderedHeight += imgHeight;
               if (renderedHeight < canvas.height) {
                 pdf.addPage();
               } // 若是后面还有内容，添加一个空页
               page.remove();
             }
             pdf.save("2024年中医医师规范化培训结业实践技能考核-准考证"+new Date().getTime()+".pdf");
             document.body.removeChild(copyDom);
             resolve();
           })
         }
})
}